# _*_ coding:utf-8 _*_
# @Time  : 2023.08.24
# @Author: zizlee
from fastapi import APIRouter, HTTPException, Query
from response import APIResponse
from utils import datetime_utils
from .doctor_tools import ExDoctorDatabase, ExchangeStatistician


class ExchangeStatistics:
    def __init__(self, fn: str, start: str, end: str):
        self.fn = fn
        self.start = datetime_utils.auth_yyyy_mm_dd(start, obj=True)
        self.end = datetime_utils.auth_yyyy_mm_dd(end, obj=True)
        if not self.start:
            raise HTTPException(status_code=422, detail='query参数`start`格式错误,接受yyyy-mm-dd类型')
        if not self.end:
            raise HTTPException(status_code=422, detail='query参数`end`格式错误,接受yyyy-mm-dd类型')
        self.start_integer = self.start.strftime('%Y%m%d')
        self.end_integer = self.end.strftime('%Y%m%d')

    def exchange_block_profit(self):
        # 板块盈亏
        database = ExDoctorDatabase(fund_num=self.fn, start=self.start_integer, end=self.end_integer)
        ex_list = database.query_exchange_statistics_data()
        if len(ex_list) < 1:
            data = {'rank_txt': '', 'rank_img': '', 'lj_img': '', 'lj_txt': ''}
        else:
            ex_statistician = ExchangeStatistician(ex_list)
            data = ex_statistician.create_block_profit_image(filename_prefix=self.fn, fig_size=(5.5, 3.75), xtick_count=12)
        return APIResponse.success(data=data)

    def exchange_struct(self):
        database = ExDoctorDatabase(fund_num=self.fn, start=self.start_integer, end=self.end_integer)
        ex_list = database.query_exchange_statistics_data()
        if len(ex_list) < 1:
            data = {'txt': '', 'img_file': '', 'txt_file': ''}
        else:
            ex_statistician = ExchangeStatistician(ex_list)
            data = ex_statistician.create_exchange_struct(filename_prefix=self.fn, fig_size=(5.5, 3.75), xtick_count=12)
        return APIResponse.success(data=data)


ex_stat_api = APIRouter()


@ex_stat_api.get('/blockProfit/')  # 板块盈亏
def exchange_block_profit(fn: str = Query(...), start: str = Query(...), end: str = Query(...)):
    return ExchangeStatistics(fn=fn, start=start, end=end).exchange_block_profit()


@ex_stat_api.get('/varietyStruct/')  # 成交结构
def exchange_struct(fn: str = Query(...), start: str = Query(...), end: str = Query(...)):
    return ExchangeStatistics(fn=fn, start=start, end=end).exchange_struct()
